package com.xl.juc.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Callable
 * 1.有返回值
 * 2.可以返回异常
 * 3.方法不同 使用call()
 * @author Charley
 * @create 2020-12-27
 */
public class CallableTest {
    public static void main(String[] args) {
       // new Thread(Runnable()).start(); 不能开启Callable线程，需要适配类FutureTask 是Runnable 的实现类
        MyThread myThread = new MyThread();
        FutureTask<String> futureTask = new FutureTask<>(myThread);
        new Thread(futureTask,"A").start();
        new Thread(futureTask,"B").start();//结果会被缓存
        try {
            String result = futureTask.get();//get方法可能产生阻塞，需要等待结果
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class MyThread implements Callable<String>{
    @Override
    public String call() throws Exception {
        return "callable ...";
    }
}
